#include "EE.h"

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

void peekRAM(int lim);
int Load(char fname[]);
void debug8080a(EEctx *R);

int main(int argc, char *argv[])
{
    if(argc < 2)
    {
    	fprintf(stderr, "Usage: %s [file]\n", argv[0]);
    	return 1;
    }

	EEctx cpu;
    reset8080a(&cpu);

    if(!Load(argv[1]))
        exit(0);

    peekRAM(20);

    exec8080a(&cpu, 30);
    debug8080a(&cpu);

    return EXIT_SUCCESS;
}

int Load(char fname[])
{
    FILE *fp = fopen(fname, "rb");

    if(fp == NULL)
    {
        fprintf(stderr, "File %s not found!\n", fname);
        return false;
    }

    fseek(fp, 0, SEEK_END);

    long size = ftell(fp);

    printf("RAM: %s [%ld bytes]\n", fname, size);

    fseek(fp, 0, SEEK_SET);

    fread(RAM, sizeof (byte), size, fp);

    fclose(fp);

    return true;
}

void peekRAM(int lim)
{
    int i;
    for(i = 0; i < lim; i++)
        printf("%X", MemRead(i));
    putchar('\n');
}

void debug8080a(EEctx *R)
{
    printf("-------CPU Status:-------------------------------------\n");

    printf("A-[0x%X] \t B/C-[0x%X/0x%X] \t "
           "D/E-[0x%X/0x%X] \t H/L-[0x%X/0x%X]\n",
           R->AF.reg.A, R->BC.reg.B, R->BC.reg.C, R->DE.reg.D,
           R->DE.reg.E, R->HL.reg.H, R->HL.reg.L);

    printf("[triton&ic]\t BC-[0x%X] \t DE-[0x%X] \t "
       "HL-[0x%X]\n",
       R->BC.pair, R->DE.pair,
       R->HL.pair);

    printf("SP-[0x%X] \t PC-[0x%X] \t \n",
        R->SP, R->PC);

    printf("------------------------------------------------------\n\n");
}
